class StudentsController < ApplicationController
  before_filter :login_required
  before_filter :unread_messages_amount, :only => [:new, :edit, :show]
  
  def new
    redirect_to schools_url unless params[:school_id]
    @school  = School.find(params[:school_id])
    @student = Student.new(:school_id => params[:school_id])
    @student.school = @school
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "没有找到学生就读的学校，请先添加学校信息"
    redirect_to schools_url
  end
  
  def create
    @student = Student.new(params[:student])
    @student.user = current_user
    @student.save!
    flash[:notice] = "添加了一个学生信息"
    redirect_to school_url(@student.school_id)
  end
  
  def edit
    @student = Student.find(params[:id])
    @school  = School.find(params[:id])
  end
  
  def update
    @student = Student.find(params[:id])
    @student.update_attributes!(params[:student])
    flash[:notice] = "成功编辑了学生信息"
    redirect_to student_url(@student.school_id, @student.id)
  end
  
  def destroy
    @student = Student.find(params[:id])
    @student.destroy
    flash[:notice] = "删除了学生信息"
    redirect_to school_url(@student.school_id)
  end
  
  def show
    @student = Student.find(params[:id])
    @school  = @student.school
    @photos = @student.photos
  end
  
  private
  def authorized?
    logged_in? && current_user.is_admin?
  end
  
  def access_denied
    flash[:notice] = "只有网站管理员才能管理学生信息"
    redirect_to schools_url
  end
end
